import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    // baseURL: 'https://myx.tianan.online',
    baseURL: 'https://myxapp.tianan.online/',
    //baseURL: 'http://113.108.219.109:9090/',
    // 超时
    timeout: 10000
})

let loading = null;
//请求拦截
service.interceptors.request.use((config) => {
    if (!config.url.includes('/study_update/')) {
        loading = ElLoading.service()
    }
    const token = JSON.parse(localStorage.getItem('token'))
    const company = localStorage.getItem('company')
    const section = localStorage.getItem('section')
    const jobId = localStorage.getItem('jobId')
    const parentSection = localStorage.getItem('parentSection')
    const employee = localStorage.getItem('userId')
    let commanyReg = localStorage.getItem('commanyReg')
    if (commanyReg) {
        config.headers['content-type'] = 'application/x-www-form-urlencoded'
    } else {
        config.headers['content-type'] = 'application/json'
    }

    if (token) {
        config.headers['Authorization'] = `JWT ${token}`;
    }
    if (company) {
        config.headers['company'] = company;
    }
    if (section) {
        config.headers['section'] = section;
    }
    if (parentSection) {
        config.headers['parent_section'] = parentSection;
    }
    if (employee) {
        config.headers['employee'] = employee;
    }

    return config;
}, (error) => {
    return Promise.reject(error);
})


service.interceptors.response.use((response) => {
    loading.close()
    if (response.data.status == 200) {
        return response.data
    } else {
        ElMessage.error(response.data.msg)
        return response.data
    }
}, (error) => {
    loading.close()
    ElMessage.error(error.response.data.msg)
    return Promise.reject(error)
})

export default service